package com.ctgu.chatapp.Service

import android.util.Log
import com.ctgu.chatapp.Netty.protocol.Message
import com.ctgu.chatapp.TaskTimerManager
import com.ctgu.chatapp.model.Database.DataBaseManager
import com.ctgu.chatapp.model.pojo.RecordNew
import com.ctgu.chatapp.view.FriendChat
import com.ctgu.chatapp.view.IMSApplication
import com.ctgu.chatapp.viewModel.StartViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class AckService {

    private val TAG = "AckService"

    fun solve(msg: Message.IMSMsg) {
        when (msg.bodyType) {
            Message.IMSMsg.BodyType.LoginResponse -> loginResponse(msg)
            Message.IMSMsg.BodyType.ChatRequest -> chatResponse(msg)
            else -> friendRequest(msg)
        }
    }

    private fun chatResponse(msg: Message.IMSMsg) {
        println(msg.head.timestamp)
        val result = TaskTimerManager.remove(msg.head.timestamp)
        if (result != null) {
            if (msg.chatRequest.contentType != Message.ChatRequest.ContextType.Control) {
                val message = android.os.Message()
                message.what = 3
                message.obj = msg
                FriendChat.handler.sendMessage(message)
                CoroutineScope(Dispatchers.IO).launch {
                    DataBaseManager.getInstance(IMSApplication.context).getMsgDao()
                        .addRecord(
                            RecordNew(
                                result.chatAck.id,
                                result.head.fromId,
                                result.head.toId,
                                0,
                                result.chatRequest.context,
                                result.head.timestamp, true
                            )
                        )
                }
            }
        }
    }

    private fun loginResponse(msg: Message.IMSMsg) {
        Log.d(TAG, "loginResponse: " + msg.head.snowFlowerID)
        println(msg.head.timestamp)
        TaskTimerManager.remove(msg.head.timestamp)
        val message = android.os.Message()
        message.what = 1
        message.obj = msg
        StartViewModel.handler.sendMessage(message)
    }

    private fun friendRequest(msg: Message.IMSMsg) {
        TaskTimerManager.remove(msg.head.timestamp)
    }
}